const DB_NAME="demo-DB-history"
const STORE_NAME='demo-history'
let DB = null

export default {
  prepare () {
    return new Promise((resolve, reject) => {
      // 打开数据库
      const request = indexedDB.open(DB_NAME)
      request.onerror = function(event) {
        reject(event)
      }
      request.onsuccess = function(event) {
        DB = event.target.result;
        resolve()
      }
      request.onupgradeneeded = function(event) {
        const db = event.target.result
        const objectStore = db.createObjectStore(STORE_NAME, { keyPath: 'url' });
        objectStore.createIndex('time', 'time', { unique: true })
      }
    })
  },
  push (url) {
    return new Promise((resolve, reject) => {
      const request = DB.transaction(STORE_NAME, "readwrite")
                        .objectStore(STORE_NAME)
                        .put({ url, time: new Date() });
      request.onerror = function(event) {
        reject(event)
      }
      request.onsuccess = function(_event) {
        resolve()
      }
    })
  },
  query (keyword='', limit = 10) {
    return new Promise((resolve, reject) => {
      const urls = []

      const cursor = DB.transaction(STORE_NAME)
                       .objectStore(STORE_NAME)
                       .index('time')
                       .openCursor(null, 'prev')
      cursor.onerror = function(event) {
        reject(event)
      }
      cursor.onsuccess = function(event) {
        const cursor = event.target.result
        if (cursor) {
          const url = cursor.value.url // cursor.key is the time
          if (!keyword || url.indexOf(keyword) != -1) {
            urls.push(url)
            if (limit && urls.length >= limit) {
              resolve(urls)
            }
          }
          cursor.continue()
        } else {
          resolve(urls)
        }
      }
    })
  }
}
